//
//  JDPhotoBrowserViewController.swift
//  JDWeiBo
//
//  Created by apple on 15/7/9.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

private let JDPhotoBrowserCellReuseIdentifier = "JDPhotoBrowserCellReuseIdentifier"

class JDPhotoBrowserViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        print(imageURLs)
    }
    
    // 完成子视图，视图 OK，collectionView OK
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        prepareLayout()
        
        // 跳转到用户选定的页面
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    func image(image :UIImage, didFinishSavingWithError error:NSError?, contextInfo :AnyObject) {
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    
    // 设置item的尺寸
    private func prepareLayout() {
        
        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    override func loadView() {
        
        view = UIView(frame: UIScreen.mainScreen().bounds)
        
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        // 在自动布局
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectionView()
    
    }
    
    // 监听 saveButton
    func save() {
        // 0. 拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! JDPhotoViewerCell
        
        // 1. 拿到图像
        let image = cell.imageView.image!
        
        // 2. 保存图像 - 回调方法的参数格式是固定的
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    // 监听 closeButton
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    private func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(JDPhotoViewerCell.self, forCellWithReuseIdentifier: JDPhotoBrowserCellReuseIdentifier)
    }
    
    // 点击关闭
    func photoViewerCellDidTapImage() {
        // 关闭界面
        close()
    }
    
    // 图像的数组
    private var imageURLs : [NSURL]
    // 用户选中照片的索引
    private var currentIndex : Int
    
    // 初始化本类的属性
    init(urls : [NSURL], index : Int) {
        
        imageURLs = urls
        
        currentIndex = index
        
        // 初始化完成属性再次调用父类的init函数
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 控件的懒加载
    lazy private var layout = UICollectionViewFlowLayout()
    
    lazy private var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    lazy private var saveButton : UIButton = {
        
       let btn = UIButton()
        
        btn.setTitle("保存", forState: UIControlState.Normal)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        return btn
    }()

    lazy private var closeButton : UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("关闭", forState: UIControlState.Normal)
        
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        return btn
    }()
}

// 分类继承 UICollectionViewDataSource 数据源
extension JDPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate, JDPhotoViewerCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(JDPhotoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! JDPhotoViewerCell
        
        cell.backgroundColor = UIColor.darkGrayColor()
        cell.imageURL = imageURLs[indexPath.item]
        
        cell.photoDelegate = self
        
        return cell
    }
}
